package com.aiyige.page.pay;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.BuildConfig;
import com.aiyige.R;
import com.aiyige.arouter.Router;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.eventbus.EventMomentChanged;
import com.aiyige.model.Subject;
import com.aiyige.model.User;
import com.aiyige.model.moment.entity.Guarantee;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.model.request.GetDeafultConponRequest;
import com.aiyige.model.response.ErrorResponse;
import com.aiyige.page.coupon.model.UserCoupon;
import com.aiyige.page.pay.adapter.GuaranteeAdapter;
import com.aiyige.page.pay.model.OrderModel;
import com.aiyige.page.pay.util.PayUtil;
import com.aiyige.page.publish.guarantee.model.GuaranteeItem;
import com.aiyige.page.webview.WebViewPage;
import com.aiyige.trace.model.Trace;
import com.aiyige.trace.util.TraceUtil;
import com.aiyige.track.TrackEvent;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.widget.LabelImageView;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.EventBus;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.aiyige.page.pay.ChooseCouponPage.CONFIRM_ORDER_PAGE_REQUEST_CODE;
import static com.aiyige.page.pay.ChooseCouponPage.NO_USE;

@Route(path = ARouterConfig.ConfirmOrderPage, extras = ARouterConfig.EXTRA_NEED_LOGIN)
public class ConfirmOrderPage extends BaseActivity {
    public static final int REQUEST_CODE_CONFIRM_PAY = 1;
    public static final int REQUEST_CODE_SELL_OUT = 2;//售罄
    public static final int UNDERSTOCK = 3;//您购买的商品库存已不足！
    public static final int MOMENT_HAS_CHANGED = 4;//您购买的商品库存已不足！
    public static final int DO_NOT_BUY_SELF_GOODS = 5;//订单验证失败，卖家不用购买自己的商品{0}！
    public static final int ORDER_GOODS_IS_EMPTY = 6;////#订单中的商品不能为空！
    public static final int CLASS_IS_STARTED = 7;//#您购买的课程已经开课，已无法购买！


    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.iv_head)
    ImageView avatarIv;
    @BindView(R.id.tv_name)
    TextView userNameTv;
    @BindView(R.id.iv_cover)
    LabelImageView coverIv;
    @BindView(R.id.tv_title)
    TextView goodsTitleTv;
    //    @BindView(R.id.goodsTypeTv)
//    TextView goodsTypeTv;
    @BindView(R.id.minusBtn)
    ImageView minusBtn;
    @BindView(R.id.goodsNumTv)
    TextView goodsNumTv;
    @BindView(R.id.plusBtn)
    ImageView plusBtn;
    @BindView(R.id.guaranteeRv)
    RecyclerView guaranteeRv;
    @BindView(R.id.guaranteeLayout)
    LinearLayout guaranteeLayout;
    @BindView(R.id.currencySymbolTv1)
    TextView currencySymbolTv1;
    @BindView(R.id.moneyTv)
    TextView moneyTv;
    @BindView(R.id.confirmTotalMoneyLabel)
    TextView confirmTotalMoneyLabel;
    @BindView(R.id.currencySymbolTv2)
    TextView currencySymbolTv2;
    @BindView(R.id.confirmMoneyTv)
    TextView confirmMoneyTv;
    @BindView(R.id.confirmOrderBtn)
    TextView confirmOrderBtn;
    @BindView(R.id.loadingLayout)
    View loadingLayout;
    @BindView(R.id.errorLayout)
    View errorLayout;
    @BindView(R.id.tv_price)
    TextView singlePriceTv;

    @BindView(R.id.tv_lineation_price)
    TextView tvLineationPrice;

    @BindView(R.id.rl_set_count)
    RelativeLayout rlSetCount;

    @BindView(R.id.ll_count)
    LinearLayout ll_count;
    @BindView(R.id.tv_date_info)
    TextView tvDateInfo;

    @BindView(R.id.consumer_protection_plan)
    View consumerPprotectionPlan;

    @BindView(R.id.tv_content_count)
    TextView tvContentCount;

    @BindView(R.id.tv_coupon_type)
    TextView tvCouponType;

    @BindView(R.id.tv_coupon_amount)
    TextView tvCouponAmount;


    @BindView(R.id.rl_coupon_select)
    RelativeLayout rlCouponSelect;


    @Autowired
    String goodsId;
    @Autowired
    String source;
    @Autowired
    String sourceUrl;
    @Autowired
    boolean multiBuy = false;
    @Autowired
    int buyNum = 1;
    @Autowired
    boolean fromH5 = false;
    @Autowired
    String h5Tid = "";
    @Autowired
    int h5Code = 0;

    int maxBuyNum = Integer.MAX_VALUE;
    OrderModel orderModel;
    GuaranteeAdapter guaranteeAdapter;
    TrackEvent trackEvent = new TrackEvent();
    boolean understock = false;// 库存不足

    Moment moment;

    UserCoupon selectedUserCoupon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_confirm_order);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        titleTv.setMaxLines(3);
        ll_count.setVisibility(View.GONE);
        tvDateInfo.setVisibility(View.GONE);
        titleTv.setText(R.string.confirm_order);
        if (TextUtils.isEmpty(goodsId)) {
            goodsId = "";
        }
        if (TextUtils.isEmpty(source)) {
            source = "";
        }
        if (TextUtils.isEmpty(sourceUrl)) {
            sourceUrl = "";
        }
        tvLineationPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
        guaranteeRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        guaranteeAdapter = new GuaranteeAdapter();
        guaranteeAdapter.bindToRecyclerView(guaranteeRv);
        guaranteeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ARouter.getInstance()
                        .build(ARouterConfig.GuaranteeShowPage)
                        .withObject("guaranteeItemArray", guaranteeAdapter.getData())
                        .navigation();
            }
        });
        loadingLayout.setClickable(true);
        plusBtn.setEnabled(multiBuy);
        minusBtn.setEnabled(multiBuy);
        requestData();
    }


    private void requestGetDefaultCoupon(String momentId, double fullAmount) {
        GetDeafultConponRequest.newBuilder().momentId(momentId).fullAmount(fullAmount).build().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (response != null && response.isSuccessful()) {
                        selectedUserCoupon = JsonUtil.toObject(response.body().string(), UserCoupon.class);
                        refreshSelectedUserCoupon();
                    } else {
                        ErrorResponse data = JsonUtil.toObject(response.errorBody().string(), ErrorResponse.class);
                        onFailure(call, new Throwable(data.getMessage()));
                    }
                } catch (Exception e) {
                    onFailure(call, e);
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                if (t != null && !TextUtils.isEmpty(t.getMessage())) {
                    ToastX.show(t.getMessage());
                }
            }
        });
    }

    public void requestData() {
        new RequestDataTask().execute();
    }

    @Override
    public void onBackPressed() {
        PayUtil.cancelOrderDialog(this)
                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ConfirmOrderPage.this.finish();
                    }
                })
                .setNegativeButton(R.string.no, null)
                .create()
                .show();
    }

    @OnClick({R.id.guaranteeLayout, R.id.guaranteeRv, R.id.errorLayout, R.id.titleBackBtn, R.id.minusBtn, R.id.plusBtn, R.id.confirmOrderBtn, R.id.consumer_protection_plan, R.id.rl_coupon_select})
    public void onViewClicked(View view) {
        if (orderModel == null) return;
        switch (view.getId()) {
            case R.id.guaranteeLayout:
            case R.id.guaranteeRv:
                ARouter.getInstance()
                        .build(ARouterConfig.GuaranteeShowPage)
                        .withObject("guaranteeItemArray", guaranteeAdapter.getData())
                        .navigation();
                break;
            case R.id.titleBackBtn:
                PayUtil.cancelOrderDialog(this)
                        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ConfirmOrderPage.this.finish();
                            }
                        })
                        .setNegativeButton(R.string.no, null)
                        .create()
                        .show();
                break;
            case R.id.minusBtn:
                orderModel.setBuyNum(Math.max(1, orderModel.getBuyNum() - 1));
                orderModel.setTotalPrice((orderModel.getCurrentPrice() * orderModel.getBuyNum()) - getCouponPrice());
                orderModel.setTotalPayPrice((orderModel.getCurrentPrice() * orderModel.getBuyNum()) - getCouponPrice());
                updateView();
                break;
            case R.id.plusBtn:
                orderModel.setBuyNum(Math.min(maxBuyNum, orderModel.getBuyNum() + 1));
                orderModel.setTotalPrice((orderModel.getCurrentPrice() * orderModel.getBuyNum()) - getCouponPrice());
                orderModel.setTotalPayPrice((orderModel.getCurrentPrice() * orderModel.getBuyNum()) - getCouponPrice());
                updateView();
                break;
            case R.id.confirmOrderBtn:
                if (understock) {

                } else {
                    User user = AccountUtil.getCurrentUser();
                    if (user != null && TextUtils.isEmpty(user.getMobile())) {
                        ARouter.getInstance().build(ARouterConfig.BindingPhonePage).navigation();
                        return;
                    }
                    trackEvent.sendEvent(this, TrackEvent.CONFIRM_ORDER, TrackEvent.CONFIRM_ORDER_LABEL);
                    String tid = "";
                    int code = 0;
                    if (fromH5) {
                        tid = h5Tid;
                        code = h5Code;
                    } else {
                        Trace trace = TraceUtil.peek();
                        if (trace != null) {
                            tid = trace.getTraceId();
                            code = trace.getCode();
                        }
                    }

                    PayUtil.createOrder(orderModel, (int) orderModel.getBuyNum(), selectedUserCoupon != null ? selectedUserCoupon.getId() : null, tid, code, new PayUtil.PayCallback() {
                        @Override
                        public void payed() {
                            finish();
                            EventBus.getDefault().post(EventMomentChanged.newBuilder().build());
                        }

                        @Override
                        public void momentChanged() {
                            finish();
                            EventBus.getDefault().post(EventMomentChanged.newBuilder().build());
                        }
                    }, this);
                }
                break;
            case R.id.errorLayout:
                requestData();
                break;
            case R.id.consumer_protection_plan:
                WebViewPage.start(BuildConfig.cspDescriptionUrl);
                break;
            case R.id.rl_coupon_select:
                ARouter.getInstance()
                        .build(ARouterConfig.ChooseCouponPage)
                        .withParcelable("selectedUserCoupon", selectedUserCoupon)
                        .withString("momentId", orderModel.getGoodsId())
                        .withDouble("fullAmount", orderModel.getCurrentPrice() * orderModel.getBuyNum())
                        .navigation(this, CONFIRM_ORDER_PAGE_REQUEST_CODE);
                break;
        }
    }


    public void updateView() {
        if (orderModel == null) return;
        Glide.with(this)
                .load(orderModel.getSellerAvatar())
                .apply(RequestOptions.placeholderOf(R.drawable.default_head))
                .apply(RequestOptions.circleCropTransform())
                .into(avatarIv);
        Glide.with(this)
                .load(orderModel.getCoverUrl())
                .into(coverIv.getImageView());
        userNameTv.setText(orderModel.getSellerName());
        switch (orderModel.getSubjectIndex()) {
            case Moment.SUBJECT_VIDEO_COURSE_INDEX:
                coverIv.setLabel(getString(R.string.learn_video));
                break;
            case Moment.SUBJECT_MAJOR_COURSE_INDEX:
                coverIv.setLabel(getString(R.string.major_course));
                break;
            case Moment.SUBJECT_TRAINING_COURSE_INDEX:
                coverIv.setLabel(getString(R.string.traing_class));
                break;
            case Moment.SUBJECT_TRAINING_CARD_INDEX:
                coverIv.setLabel(getString(R.string.traing_card));
                break;
            default:
                coverIv.getLabelTv().setVisibility(View.INVISIBLE);
                break;
        }
        singlePriceTv.setText("￥" + ( StringUtils.priceFormat(orderModel.getCurrentPrice())));
        tvLineationPrice.setText(orderModel.hasLinePrice()?"￥" + StringUtils.priceFormat(orderModel.getSinglePrice()):"");
        goodsTitleTv.setText(orderModel.getTitle());
        goodsNumTv.setText(orderModel.getBuyNum() + "");
        guaranteeLayout.setVisibility(ListUtil.isEmpty(orderModel.getGuaranteeItemList()) ? View.GONE : View.VISIBLE);
        guaranteeAdapter.setNewData(orderModel.getGuaranteeItemList());
        moneyTv.setText(StringUtils.priceFormat(orderModel.getTotalPrice()));
        confirmMoneyTv.setText(StringUtils.priceFormat(orderModel.getTotalPayPrice()));
        if (!TextUtils.isEmpty(orderModel.getSubject()) && orderModel.getSubject().equals(Subject.video_course)) {
            rlSetCount.setVisibility(View.GONE);
        }
        consumerPprotectionPlan.setVisibility(moment != null && moment.isConsumptionGuarantee() ? View.VISIBLE : View.GONE);
        confirmMoneyTv.setText(StringUtils.priceFormat(orderModel.getTotalPayPrice()));
        if (!TextUtils.isEmpty(orderModel.getContentCountString())) {
            tvContentCount.setVisibility(View.VISIBLE);
            tvContentCount.setText(orderModel.getContentCountString());
        } else {
            tvContentCount.setVisibility(View.INVISIBLE);
        }

        requestGetDefaultCoupon(orderModel.getGoodsId(), orderModel.getCurrentPrice() * orderModel.getBuyNum());
    }

    private double getCouponPrice() {
        return selectedUserCoupon != null ? selectedUserCoupon.getCouponAmount() : 0;
    }

    public class RequestDataTask extends AsyncTask<Object, Object, Object> {
        @Override
        protected void onPreExecute() {
            loadingLayout.setVisibility(View.VISIBLE);
            errorLayout.setVisibility(View.INVISIBLE);
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().getMoment(goodsId).execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                } else {
                    String json = RetrofitUtil.getResponseBodyAsString(response);
                    Moment respMoment = JSON.parseObject(json, Moment.class);
                    moment = new Moment(respMoment);
                    ConfirmOrderPage.this.moment = moment;
                    maxBuyNum = moment.getInventoryBackup().getAvailableInventory().intValue();
                    List<GuaranteeItem> guaranteeItemList = new LinkedList<>();
                    try {
                        for (Guarantee guarantee : moment.getDetailBackup().getGuarantee()) {
                            guaranteeItemList.add(GuaranteeItem.newBuilder()
                                    .id(guarantee.getId())
                                    .content(guarantee.getDetail())
                                    .title(guarantee.getName())
                                    .selected(true)
                                    .build());
                        }
                    } catch (Exception e) {

                    }
                    orderModel = OrderModel.newBuilder()
                            .buyNum(buyNum)
                            .coverUrl(ListUtil.isEmpty(moment.getCover()) ? "" : moment.getCover().get(0))
                            .goodsId(goodsId)
                            .sellerAvatar(moment.getCreatorBackup().getAvatar())
                            .sellerName(moment.getCreatorBackup().getName())
                            .sellerId(moment.getCreatorBackup().getId())
                            .source(source)
                            .sourceUrl(sourceUrl)
                            .singlePrice(moment.getCommodityBackup().getPrice())
                            .lineSinglePrice(moment.getOnSalesBackup().hasLinePrice() ? moment.getOnSalesBackup().getPrice() : null)
                            .totalPrice((moment.getCommodityBackup().getPrice() * buyNum) - getCouponPrice())
                            .totalPayPrice((moment.getCommodityBackup().getPrice() * buyNum) - getCouponPrice())
                            .subject(moment.getSubject())
                            .subjectIndex(moment.getSubjectIndex())
                            .title(moment.getTitle())
                            .guaranteeItemList(guaranteeItemList.subList(0, Math.min(guaranteeItemList.size(), 4)))
                            .version(moment.getVersion())
                            .contentCountString(OrderModel.getContentValue(moment))
                            .build();
                }
                return null;
            } catch (Exception e) {
                return e;
            }

        }

        @Override
        protected void onPostExecute(Object o) {
            loadingLayout.setVisibility(View.INVISIBLE);
            if (o instanceof Exception) {
                errorLayout.setVisibility(View.VISIBLE);
                ToastX.show(((Exception) o).getMessage());
            } else {
                updateView();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        understock = false;
        switch (resultCode) {
            case RESULT_OK:
                finish();
                break;
            case REQUEST_CODE_CONFIRM_PAY:
            case DO_NOT_BUY_SELF_GOODS:
                finish();
                break;
            case REQUEST_CODE_SELL_OUT://售罄
            case MOMENT_HAS_CHANGED://订单发生变化
            case UNDERSTOCK://库存不足
//                understock = true;
//                requestData();
//
                if (moment != null) {
                    Router.start(moment.getRouter());
                }
                finish();
                break;
            case CONFIRM_ORDER_PAGE_REQUEST_CODE:
                if (data != null && data.getParcelableExtra("userCoupon") != null) {
                    selectedUserCoupon = data.getParcelableExtra("userCoupon");
                    refreshSelectedUserCoupon();
                }
                break;
            case NO_USE:
                selectedUserCoupon = null;
                refreshSelectedUserCoupon();
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    private void refreshSelectedUserCoupon() {
        if (orderModel != null) {
            orderModel.setTotalPrice((orderModel.getCurrentPrice() * orderModel.getBuyNum()) - getCouponPrice());
            orderModel.setTotalPayPrice((orderModel.getCurrentPrice() * orderModel.getBuyNum()) - getCouponPrice());
            confirmMoneyTv.setText(StringUtils.priceFormat(orderModel.getTotalPayPrice()));
        }
        if (selectedUserCoupon != null) {
            tvCouponType.setText(selectedUserCoupon.getCouponName());
            tvCouponAmount.setText("-￥" + selectedUserCoupon.getCouponAmount());
        } else {
            tvCouponType.setText(getResources().getString(R.string.the_current_is_to_use_coupons));
            tvCouponAmount.setText("");
        }
    }
}
